#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import sys, datetime, json, logging
import pandas as pd

from xpy3lib.XRetryableQuery import XRetryableQuery
from xpy3lib.XRetryableSave import XRetryableSave
from sicost.AbstractDPJob import AbstractDPJob


class LOGJob(AbstractDPJob):
    """
    通过两个SQL去取来源表和目标表的表结构

    传入6个参数   来源标  和目标表  及开始时间结束时间

    将来源表那段时间的数据取出来  在存到目标表里
    """
    job_name = None
    start = None
    status = None
    param_info = None
    def __init__(self,
                 p_config=None,
                 p_db_conn_rds=None,
                 p_job_name=None,p_start=None,p_status=None,p_param_info=None):


        super(LOGJob, self).__init__(p_config=p_config,
                                        p_db_conn_mpp=None,
                                        p_db_conn_rds=p_db_conn_rds,
                                        p_db_conn_dbprod7=None,
                                        p_unit=None,
                                        p_account=None,
                                        p_cost_center=None,
                                        p_account_period_start=None,
                                        p_account_period_end=None)
        self.job_name = p_job_name
        self.start = p_start
        self.status = p_status
        self.param_info = p_param_info

        pass

    def do_execute(self):
        """
        """
        self.logger.info('LOGJob.do_execute')
        if self.status == 'start':
            start_time = self.start.strftime('%Y%m%tmp_dict%H%M%S')

            df0 = pd.DataFrame(columns=('JOB_NAME', 'START_TIMESTAMP', 'REC_CREATE_TIME'))


            df0 = df0.append([{'JOB_NAME': self.job_name, 'START_TIMESTAMP': start_time, 'REC_CREATE_TIME': start_time}], ignore_index=True)

            XRetryableSave(p_db_conn=self.db_conn_rds, p_table_name='T_PUB_LOG_JOBS', p_schema='BGTARAS1',
                           p_dataframe=df0,
                           p_max_times=5).redo()
        if self.status == 'update':
            end = datetime.datetime.now()
            start_time = self.start.strftime('%Y%m%tmp_dict%H%M%S')
            end_time = end.strftime('%Y%m%tmp_dict%H%M%S')
            #elapsed = float((end_time - start_time).seconds)
            elapsed = float((end - self.start).seconds)
            sql = " UPDATE  ( " \
                  " select * from BGTARAS1.T_PUB_LOG_JOBS where JOB_NAME='%s' and START_TIMESTAMP='%s' and REC_CREATE_TIME='%s' " \
                  " ) as t1 SET t1.LAST_TIMESTAMP='%s' , t1.ELAPSED='%s' , t1.IS_SUCCESSFUL='T' , t1.PARAM_INFO= '%s' " % (
                  self.job_name, start_time, start_time, end_time, elapsed, self.param_info)
            print(sql)
            self.logger.info(sql)
            self.db_conn_rds.execute(sql)





        super(LOGJob, self).do_execute()